// vp_ju/pages/user/settings.js
var app = getApp();

Page({
  data: {
    form: {
      description: '',
      images: [],
      files: [],
      contactName: '',
      contactPhone: '',
	  selectHospital:0,
	  selectKeshi:0,
    },
    formValid: false,
	hospitalList: [{id:-1,name:'请选择医院'}],    // 医院列表
	hospitalIndex: 0,   // 当前选中医院索引
	currentHospital:null,
	currentDepartment:null,
	departmentList: [],  // 科室列表
	departmentIndex: 0, // 当前选中科室索引
  },

  // 输入处理
  onDescChange(e) {
    this.setData({ 'form.description': e.detail.value }, this.validateForm)
  },
  onNameChange(e) {
    this.setData({ 'form.contactName': e.detail.value }, this.validateForm)
  },
  onPhoneChange(e) {
    this.setData({ 'form.contactPhone': e.detail.value }, this.validateForm)
  },

  // 图片操作
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.form.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
	  const newImages = res.tempFilePaths.map(tempUrl => ({
		  tempUrl,       // 新增临时路径字段
		  url: '',       // 服务器路径初始为空
		  status: 'pending',
		  progress: 0
		}))
		this.setData({ 'form.images': [...this.data.form.images, ...newImages] })
		this.uploadFiles('image',res.tempFilePaths)
      }
    })
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.form.images.filter((_, i) => i !== index)
    this.setData({ 'form.images': images }, this.validateForm)
  },

  // 文件操作
  chooseFile() {
    wx.chooseMessageFile({
      count: 5,
      type: 'all',
      success: res => {
        const newFiles = res.tempFiles.map(file => ({
          name: file.name,
          size: this.formatFileSize(file.size),
          path: file.path
        }))
        this.setData({ 'form.files': [...this.data.form.files, ...newFiles] })
		this.uploadFiles('file',res.tempFiles)
      }
    })
  },

  deleteFile(e) {
    const index = e.currentTarget.dataset.index
    const files = this.data.form.files.filter((_, i) => i !== index)
    this.setData({ 'form.files': files })
  },

  // 文件大小格式化
  formatFileSize(bytes) {
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + 'MB'
    return (bytes / 1024).toFixed(0) + 'KB'
  },

  // 统一上传方法
  uploadFiles(field, tempFilePaths) {
	  var url = app.util.url('Common/upload');
	  console.log(tempFilePaths)
    tempFilePaths.forEach((tempFilePath, index) => {
		if(field !== 'image'){
			tempFilePath = tempFilePath.path
		}
      const uploadTask = wx.uploadFile({
        url: url,
        filePath: tempFilePath,
        name: 'file',
        success: res => {
          const data = JSON.parse(res.data)
          this.updateFileStatus(field, index, 'done', data.data.path)
        },
        fail: () => {
          this.updateFileStatus(field, index, 'error')
          wx.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    })
  },

  updateFileStatus(field, index, status, url = '') {
    const path = `form.${field}[${index}]`
    this.setData({
      [path + '.status']: status,
      [path + '.url']: url
    }, this.validateForm)
  },
onLoad() {
    this.loadHospitals()
  },

  // 加载医院列表
  loadHospitals() {
	  let that = this
    try {
      app.util.request({
              url: 'Hospital/kuajinglists',
			  method: 'GET',
              data: {},
			  success(res){
				  that.setData({
				    hospitalList: res.data.data.hospital.map(item => ({
				      id: item.id,
				      name: item.name
				    }))
				  })
			  }
      })
    } catch (error) {
      wx.showToast({ title: '加载医院失败', icon: 'none' })
    }
  },

  // 医院选择变化
  async onHospitalChange(e) {
    const index = e.detail.value
    this.setData({ 
      // hospitalIndex: index,
      departmentIndex: -1  // 重置科室选择
    })
    this.setData({
      currentHospital: this.data.hospitalList[e.detail.value].name,
      'form.selectHospital': this.data.hospitalList[e.detail.value].id
    }, this.validateForm)
	let that = this
    try {
		const res = await app.util.request({
              url: 'Hospital/kuajingkeshilists',
			  method: 'GET',
              data: {
				  hospital_id:that.data.hospitalList[index].id
              },
			  success(res){
				  console.log(res)
				    that.setData({
				      departmentList: res.data.data.keshi.map(item => ({
				        id: item.id,
				        name: item.name
				      }))
				    })
			  }
      })
	
    } catch (error) {
      wx.showToast({ title: '加载科室失败', icon: 'none' })
      this.setData({ departmentList: [] })
    }
  },

  // 科室选择变化
  onDepartmentChange(e) {
    // this.setData({ departmentIndex: e.detail.value })
	this.setData({
	  currentDepartment: this.data.departmentList[e.detail.value]?.name,
	  'form.selectKeshi': this.data.departmentList[e.detail.value]?.id
	}, this.validateForm)
  },
  // 表单验证
  validateForm() {
    const valid = this.data.form.selectHospital >= 0 &&
                 this.data.form.selectKeshi >= 0 &&
				 this.data.form.description.trim().length >= 0 &&
                 this.data.form.images.length > 0 &&
                 /^[\u4e00-\u9fa5]{2,10}$/.test(this.data.form.contactName) &&
                 /^1[3-9]\d{9}$/.test(this.data.form.contactPhone)
    this.setData({ formValid: valid })
  },

  // 提交表单
  async handleSubmit() {
    if (!this.data.formValid) return

    try {
      wx.showLoading({ title: '提交中...' })
       const selectedHospital = this.data.hospitalList[this.data.hospitalIndex]
       const selectedDepartment = this.data.departmentList[this.data.departmentIndex]
	   console.log(this.data.form)
	   const image = [];
	   const file = [];
	   this.data.form.image.map(function(item){
		   image.push(item.url)
	   })
	   this.data.form.file.map(function(item){
		   file.push(item.url)
	   })
      // 构造提交数据
      const submitData = {
		hospital_name: this.data.currentHospital,
		department_name: this.data.currentDepartment,
        ...this.data.form,
        image: JSON.stringify(image),
        file: JSON.stringify(file)
      }
      // 模拟提交
	  await app.util.request({
		  url: 'Kjyl/uploadcase',
		  data: submitData,
		  success(res) {
			  wx.showModal({
				  title:'提交成功',
				  content: res.data.msg,
				  confirmText: '确定',
				  showCancel: false,
				  success:function(){
					  wx.navigateTo({
						url: `/vp_pz/pages/user/index`
					  })
					 
				  }
			  });
		  }
	  })
      wx.hideLoading()
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        complete: () => {
          setTimeout(() => wx.navigateBack(), 1500)
        }
      })
    } catch (error) {
      wx.hideLoading()
      wx.showToast({ title: '提交失败', icon: 'none' })
    }
  },
})